package mall.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import mall.bean.Cart;
import mall.bean.CartPK;
import mall.dao.CartDao;

public class CartDaoImpl implements CartDao {

	@Override
	public void save(Cart obj) {
		String sql = "INSERT INTO cart (pid, uid, quantity) VALUES (?, ?, ?)";
		JdbcTemplate.update(sql, obj.getPid(), obj.getUid(), obj.getQuantity());
	}

	@Override
	public void delete(CartPK id) {
		String sql = "DELETE FROM cart WHERE pid = ? AND uid = ?";
		JdbcTemplate.update(sql, id.getPid(), id.getUid());
	}

	@Override
	public void update(Cart obj) {
		String sql = "UPDATE cart SET quantity = ? WHERE pid = ? AND uid = ?";
		JdbcTemplate.update(sql, obj.getQuantity(), obj.getPid(), obj.getUid());
	}

	@Override
	public Cart findById(CartPK id) {
		String sql = "SELECT pid, uid, quantity FROM cart WHERE pid = ? AND uid = ?";
		return JdbcTemplate.query(new BeanHandler<Cart>(Cart.class), sql, id.getPid(), id.getUid());
	}

	@Override
	public long count() {
		String sql = "SELECT COUNT(1) FROM cart";
		return JdbcTemplate.query(new ScalarHandler<Long>(), sql);
	}
	
	@Override
	public List<Cart> findByUid(long uid) {
		String sql = "SELECT pid, uid, quantity FROM cart WHERE uid = ?";
		return JdbcTemplate.query(new BeanListHandler<Cart>(Cart.class), sql, uid);
	}

}
